package com.trytech.mongoocrawler.web.controller;

import com.trytech.mongoocrawler.common.enums.CrawlerStatus;
import com.trytech.mongoocrawler.web.common.CommResp;
import com.trytech.mongoocrawler.web.common.RespStatus;
import com.trytech.mongoocrawler.web.exception.BizException;
import com.trytech.mongoocrawler.web.service.CrawlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jiangtao@meituan.com
 * @since: Created on 2018年07月15日
 */
@Controller
@RequestMapping("/crawler")
public class CrawlerController extends BaseController {
    @Autowired
    private CrawlerService crawlerService;
    private boolean isCrawlerRunning = false;
    private String crawlIp;
    @RequestMapping("/crawl")
    public @ResponseBody
    CommResp crawl(HttpServletRequest request) {
        //获取客户端的ip
        String ip = request.getRemoteAddr();
//        if(isCrawlerRunning && StringUtils.isNotEmpty(crawlIp)){
//            if(crawlIp.equals(ip)){
//                return CommResp.resp(RespStatus.CRAWLER_RUNNING_ERROR);
//            }else {
//                return CommResp.resp(RespStatus.CRAWLER_OCUPPIED_BY_OTHERS_ERROR);
//            }
//        }
        crawlIp = ip;
        try {
            CrawlerStatus status = crawlerService.crawl();
            if (status != null) {
                if (CrawlerStatus.RUNNING.equalsTo(status)) {
                    return CommResp.resp(RespStatus.CRAWLER_RUNNING_ERROR);
                } else {
                    return CommResp.OK();
                }
            }

            return CommResp.resp(RespStatus.CRAWLER_SERVICE_ERROR);
        } catch (BizException e) {
            return CommResp.resp(RespStatus.CRAWLER_SERVICE_ERROR);
        }
    }
}
